package main

/*
#include <string.h>
#include <stdlib.h>

char * str_in_c = "this is C string";
char cCharArr[] = "C char array";
*/
import "C"

import (
	"fmt"
	"unsafe"
)

func main() {
	var sz C.size_t
	gostr0 := "this is Go string"
	cstr := C.CString(gostr0)
	defer C.free(unsafe.Pointer(cstr)) //go字符串被C.CString()转换成C字符串后，就脱离gc控制,需要C.free(). 前面#include <stdlib.h>这里的C.free()才可以检测到
	sz = C.strlen(cstr)
	fmt.Printf("1. C.strlen(), len of %q: %d bytes.  Type of sz: %[2]T\n\n", gostr0, sz)

	gostr1 := C.GoString(C.str_in_c)
	fmt.Printf("2. C string -> Go string by C.GoString(*C.char): %q\n\n", gostr1)

	gostr2 := C.GoString(&C.cCharArr[0])
	fmt.Printf("3. C char array -> Go string: %q\n\n", gostr2)
}
